<?php


namespace app\admin\service;


use app\common\Log;

use app\common\Pay\SafePay;

use app\utility\HttpHelper;

/**
 * 支付
 * Class InPayService
 * @package App\Admin\Services
 */
class InPayService
{

    const URL = '/web/pay_union_score';


    public static function switchThirdPay($data)
    {
        if (!$data) return [];
        switch ($data['payType']) {
            case 6:
            case 4:
                $pay = new SafePay(config('pay.safe_pay'));
                $data = $pay->pay($data);
                break;

            default:
        }
        return $data;


    }


    /**
     * 支付成功
     * @param PayOrderModel $order
     * @param string $err
     * @return bool
     */
    public static function success(PayOrderModel $order, &$err = '')
    {
        $ret = HttpHelper::post(config('custom.server_url') . self::URL, json_encode(['order_id' => $order->OrderNo]));
        $TradeNo = PayOrderModel::query()->where('OrderNo', $order->OrderNo)->value('TradeNo');
        $ret = json_decode($ret, true);
        Log::write('safepay通知服务器：' . json_encode($ret), 'pay', 'pay');

        if ($ret['ReturnCode'] == 0) {
//            $app_id = PayOrderModel::query()->where('OrderNo', $order->OrderNo)->value('app_id');
//            if ($app_id == 1000) {
//                BaseModel::selectMy('call complete_order(' . '"' . $order->OrderNo . '","' . $TradeNo . '")');
//            }
            PayOrderModel::query()->where('OrderNo', $order->OrderNo)->update(['OrderStatus' => 1, 'Remark' => '充值成功']);
            return true;
//            admin_success('操作成功');
//            return back();
        } else {
            $err = '通知服务器失败';
            Log::write('通知服务器失败，订单号：' . $order->OrderNo, 'pay', 'pay');
            return false;
//            admin_error('操作失败');
//            return back();
        }

    }


    /**
     * 支付失败
     * @param PayOrderModel $order
     * @param string $err
     * @return bool
     */
    public static function error(PayOrderModel $order, &$err = '')
    {
        try {
            PayOrderModel::query()->where('OrderNo', $order->OrderNo)->update([
                'OrderStatus' => PayOrderModel::STATUS_UNUSUAL,
                'Remark' => $order->Remark
            ]);
            return true;
        } catch (\Exception $e) {
            $err = $e->getMessage();
            return false;
        }
    }
}